package com.itheima.health.advice;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.QueryPageBean;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sun.rmi.runtime.Log;

@Slf4j
@Component
@Aspect
public class Advice_redis {
    @Autowired
    private RedisTemplate redisTemplate;
    //全限定类名
    private String httpClass;
    //方法名
    private String classmethod;

    @Pointcut("execution(* com.itheima.health.service.impl.*.*(..))")
    public void AopMethod() {

    }


    @AfterReturning("AopMethod()")
    public void before(JoinPoint joinpoint) throws Throwable {
        /*
        * @Date: 10:50 上午 2021/1/22
        * @name: before
        * @param: [joinpoint]
        * @return: void
        * @Description: 使用切面对下面三个类的所有update、add和delete方法进行清除缓存处理
        */
        //获取全限定类名  com.itheima.health.service.impl.CheckItemServiceImpl
        httpClass = joinpoint.getSignature().getDeclaringTypeName();
        //获取方法名  update
        classmethod = joinpoint.getSignature().getName();

        log.info("httpClass:{}", httpClass);
        log.info("classmethod:{}", classmethod);

        if (StringUtils.hasLength(httpClass) && StringUtils.hasLength(classmethod)) {

            String[] cla = httpClass.split("\\.");
            //判断类名
            if (cla[cla.length-1].equals("CheckGroupServiceImpl")||cla[cla.length-1].equals("CheckItemServiceImpl")||cla[cla.length-1].equals("SetMealServiceImpl")){
                //判断方法名
                if (classmethod.contains("update") || classmethod.contains("add") || classmethod.contains("delete")) {
                    log.info("[redis-切面] - 访问update||add|delete - 开始清除redis中缓存数据");
                    /*
                    使用redis的hash存储key为id，出现变化之后直接暴力删除
                     */
                    redisTemplate.delete(RedisConst.FIND_SETMEAL_ALL);
                    redisTemplate.delete(RedisConst.FIND_SETMEAL_DETAIL);
                }
            }
        }
    }
}
